import React, {
  forwardRef,
  useEffect,
  useImperativeHandle,
  Ref,
  useState,
  useCallback,
  useMemo,
} from 'react';
import Cookies from 'js-cookie';
import { useEvents } from '@inbiz/utils';
import api from './api';
import { defaultProps } from '../../designer/web/schema';
import { inbiz } from '@inbiz/core';
import { CloseCircleFilled } from '@ant-design/icons';
import SelectExtend, { DropDownRender } from './components/SelectExtend';
import MemberSelect, {
  search as oldsearch,
  getTabKeyByData,
  genKey,
  getServiceTabKey,
  positionSelector,
  getMemberIconByKey,
} from '@inbiz/basic/MemberSelect';
import { PlusCircleOutlined } from '@ant-design/icons';
import { Tag } from 'antd';
import { observer } from '@formily/react';
import { useForceUpdate } from '@inbiz/hooks';
import { getMemberInfo } from './service';
import { MemberTypeKeyMap } from './consts';
import _ from 'lodash';
import { getLowercase, nameFormat } from './util';
import { getMessage, TextWidget } from '@inbiz/react';
import { tabsData } from '../../designer/web/schema';
import './index.less';

interface IMember {
  [x: string]: any;
  key: string;
  name: string;
}
[];

export type IProps = {
  placeholder?: string;
  modalTitle?: string;
  value?: IMember[];
  viewMode?: string;
  originValue?: string | string[];
  callBackEvents?: {
    onChange?: (v: any) => void;
    onCustomConfirm?: (data: any[]) => boolean | Promise<boolean> | undefined;
    // 搜索
    onSearchParams?: (params: any) => Promise<any>;
    onSearchRequest?: (params: any) => Promise<any>;
    onSearchData?: (params: any) => Promise<any>;
    // 获取顶级部门
    onGetTopDepartmentsParams?: (params: any) => Promise<any>;
    onGetTopDepartmentsRequest?: (params: any) => Promise<any>;
    onGetTopDepartmentsData?: (params: any) => Promise<any>;
    // 获取部门列表
    onGetDepartmentsParams?: (params: any) => Promise<any>;
    onGetDepartmentsRequest?: (params: any) => Promise<any>;
    onGetDepartmentsData?: (params: any) => Promise<any>;
    // 获取子部门
    onGetSubDepartmentsParams?: (params: any) => Promise<any>;
    onGetSubDepartmentsRequest?: (params: any) => Promise<any>;
    onGetSubDepartmentsData?: (params: any) => Promise<any>;
    // 获取顶级职位
    onGetTopPositionsParams?: (params: any) => Promise<any>;
    onGetTopPositionsRequest?: (params: any) => Promise<any>;
    onGetTopPositionsData?: (params: any) => Promise<any>;
    // 获取职位列表
    onGetPositionsParams?: (params: any) => Promise<any>;
    onGetPositionsRequest?: (params: any) => Promise<any>;
    onGetPositionsData?: (params: any) => Promise<any>;
    // 获取子职位
    onGetSubPositionsParams?: (params: any) => Promise<any>;
    onGetSubPositionsRequest?: (params: any) => Promise<any>;
    onGetSubPositionsData?: (params: any) => Promise<any>;
    // 获取用户组列表
    onGetGroupsParams?: (params: any) => Promise<any>;
    onGetGroupsRequest?: (params: any) => Promise<any>;
    onGetGroupsData?: (params: any) => Promise<any>;
    // 搜索用户组
    onSearchGroupsParams?: (params: any) => Promise<any>;
    onSearchGroupsRequest?: (params: any) => Promise<any>;
    onSearchGroupsData?: (params: any) => Promise<any>;
    // 获取部门下的用户
    onGetDepartmentUsersParams?: (params: any) => Promise<any>;
    onGetDepartmentUsersRequest?: (params: any) => Promise<any>;
    onGetDepartmentUsersData?: (params: any) => Promise<any>;
    // 获取用户组下的用户
    onGetGroupUsersParams?: (params: any) => Promise<any>;
    onGetGroupUsersRequest?: (params: any) => Promise<any>;
    onGetGroupUsersData?: (params: any) => Promise<any>;
  };
  emit?: {
    (type: 'onLoad', ...args: any): void;
    (type: 'onOpen', ...args: any): void;
    (type: 'onClose', confirm: boolean): void;
    (type: 'onBeforeClose', confirm: boolean): void;
    (type: 'onBeforeOpen', ...args: any): void;
    (type: 'onSelect', ...args: any): void;
    (type: 'onBeforeChange', ...args: any): void;
    (type: 'onChange', ...args: any): void;
  };
  inbiz: inbiz;
  onChange: (v: any) => void;
  tabs: any[];
  pageSize: number;
  multiple: boolean;
  multipleMaxHeight: string;
  className?: string;
  departmentFilteringRules: string;
  departments: {
    [x: string]: any;
    IdentityId: number;
  }[];
  groupFilteringRules?: string;
  groups: {
    [x: string]: any;
    IdentityId: number;
  }[];
  disabled?: boolean;
  readOnly?: boolean;
  controlId: string;
  childModelConfig: boolean;
  storageConfig?: {
    business: string;
    tableData: {
      componentAttr: string;
      modelAttr: string;
    }[];
  };
  defaultValueType: String;
  memberDefaultValue: any;
  collectivization: Boolean;
} & typeof defaultProps;

type IRef = Ref<ReturnType<typeof api>>;

let timeout: any;

const EformMemberSelect: React.ForwardRefExoticComponent<IProps> &
  IDefaultValueFormat<{ defaultValue: any }> = observer((props) => {
    const {
      value,
      callBackEvents,
      emit,
      tabs = tabsData,
      pageSize: propPageSize,
      multiple = true,
      className,
      departmentFilteringRules,
      departments,
      groupFilteringRules,
      groups,
      placeholder='EformMemberSelect.lang.plzSelect',
      originValue,
      defaultValueType,
      memberDefaultValue,
      inbiz,
      collectivization,
      viewMode,
      multipleMaxHeight = 200,
      ref,
      ...other
    } = props;
    
    const pageSize = propPageSize > 0 ? propPageSize : 10;
    const forceUpdate = useForceUpdate();
    const [configEvents] = useEvents(props.callBackEvents, props.emit);
    const [memberSelectVisible, _memberSelectVisible] = useState(false);
    const [open, _open] = useState(false);
    const [searching, _searching] = useState(false);
    const [searchValue, _searchValue] = useState('');
    const [inlineEditContent, $inlineEditContent] = useState<any>('');
    const [searchData, _searchData] = useState([]);

    useEffect(() => {
      $inlineEditContent((Array.isArray(value) ? value : []).map((ele) => ele.name));
    }, [value]);

    const search = useCallback(async (params: object) => {
      const newParams = (await configEvents.current?.onSearchParams?.(params)) || params;
      const data = await (configEvents.current?.onSearchRequest || oldsearch)(newParams as any);
      return await configEvents.current?.onSearchData?.(data) || data;
    }, []);

    const valueKeys = Array.isArray(value) ? value.map((v) => v.key) : [];
    const _tabs = useMemo(() => {
      if (tabs && tabs?.length == 0) {
        return tabsData;
      }
      if (typeof tabs?.[0] == 'string') {
        let __tabs = tabsData?.filter((item: any) => tabs?.includes(item?.memberKey));
        return __tabs;
      }
      return tabs?.filter((item: any) => !item?.hide);
    }, [tabs]);

    const departmentDisplayFormat = useMemo(() => {
      return _tabs?.find((item: any) => item?.memberKey == 'department')?.titleDisplayFormat;
    }, [_tabs]);

    const positionDisplayFormat = useMemo(() => {
      return _tabs?.find((item: any) => item?.memberKey == 'position')?.titleDisplayFormat;
    }, [_tabs]);

    const userDepartmentDisplayFormat = useMemo(() => {
      return _tabs?.find((item: any) => item?.memberKey == 'user')?.departmentDisplayFormat;
    }, [_tabs]);

    const userUserGroupDisplayFormat = useMemo(() => {
      return _tabs?.find((item: any) => item?.memberKey == 'user')?.userGroupDisplayFormat;
    }, [_tabs]);

    const topDepartmentIds = useMemo(() => {
      let _topDepartmentIds: number[] = [];
      departments?.map?.((v) => {
        if (v.hasOwnProperty('identityid')) {
          _topDepartmentIds.push(v.identityid);
        }
      });
      // if (!_topDepartmentIds.length) {
      //   _topDepartmentIds.push(1);
      // }
      return _topDepartmentIds;
    }, [departments]);

    const groupsIds = useMemo(() => {
      let _groupsIds: number[] = [];
      groups?.map?.((v) => {
        if (v.hasOwnProperty('identityid')) {
          _groupsIds.push(v.identityid);
        }
      });
      return _groupsIds;
    }, [groups]);

    const topPositionIds = useMemo(() => {
      let _topPositionIds: number[] = [];
      departments?.map?.((v) => {
        if (v.hasOwnProperty('positionid')) {
          _topPositionIds.push(v.positionid == 0 ? 1 : v.positionid);
        }
      });
      // if (!_topPositionIds.length) {
      //   _topPositionIds.push(1);
      // }
      return _topPositionIds;
    }, [departments]);

    const searchDeptId = useMemo(() => {
      if (collectivization) {
        return Cookies.get('orgIdentityId') ? [Cookies.get('orgIdentityId')] : [1];
      }
      return topDepartmentIds;
    }, [collectivization, topDepartmentIds]);

    const searchParams = useMemo(() => {
      let _params: any = {
        topNum: pageSize,
        tabs: _tabs.map(getServiceTabKey).join(','),
      }
      if (collectivization) {
        _params['searchDeptId'] = '1';
        _params['searchPositionId'] = '1';
      } else {
        if (departments?.length == 0) {
          _params['searchDeptId'] = '1';
          _params['searchPositionId'] = '1';
        } else {
          if (departmentFilteringRules == 'exceptSelected') {
            _params['banDeptIds'] = topDepartmentIds?.join(',');
            _params['banPositionIds'] = topPositionIds?.join(',');
          } else {
            _params['searchDeptId'] = topDepartmentIds?.join(',');
            _params['searchPositionId'] = topPositionIds?.join(',');
          }
        }
        if (groups?.length != 0) {
          if (groupFilteringRules == 'exceptSelected') {
            _params['banGroupIds'] = groupsIds?.join(',');
          } else {
            _params['searchGroupId'] = groupsIds?.join(',');
          }
        }
      }
      return _params;
    }, [pageSize, searchDeptId, topPositionIds, _tabs, departmentFilteringRules, departments, topDepartmentIds, groupFilteringRules, groupsIds, collectivization]);

    const addItem = useCallback(
      (item) => {
        let newValue: any = Array.isArray(value) ? value : [];
        if (multiple) {
          let index = newValue.map((v) => v.key).indexOf(item.key);
          if (index == -1) {
            newValue.push(item);
            props.onChange([...newValue]);
            forceUpdate();
          }
        } else {
          newValue = [item];
          props.onChange(newValue);
          forceUpdate();
        }
      },
      [value, props.onChange, multiple],
    );

    const removeItem = useCallback(
      (key: string) => {
        if (multiple) {
          let newValue: any = Array.isArray(value) ? value : [];
          let index = newValue.map((v) => v.key).indexOf(key);
          if (index > -1) {
            newValue.splice(index, 1);
            props.onChange([...newValue]);
            forceUpdate();
          }
        } else {
          props.onChange([]);
          forceUpdate();
        }
      },
      [value, props.onChange, multiple],
    );

    const transSearchData = (data) => {
      const key = genKey(getTabKeyByData(data), data);
      return {
        label: nameFormat(
          data,
          departmentDisplayFormat,
          positionDisplayFormat,
          userDepartmentDisplayFormat,
          userUserGroupDisplayFormat,
        ),
        value: key,
        key: key,
        data: data,
      };
    };

    useImperativeHandle(
      ref,
      () => ({
        ...api(configEvents, props),
        setMemberVisiable: _memberSelectVisible,
      }),
      [props],
    );

    const onDropdownItemClick = useCallback(
      (item, checked) => {
        _open(false);
        _searchValue('');
        setTimeout(() => {
          _searchData([]);
        }, 250);
        if (
          _tabs?.find((item: any) => item?.id == 'eformMemberSelectUser')?.positionSelect &&
          item?.key?.startsWith('user') &&
          checked
        ) {
          //需要选择职位
          positionSelector({
            users: [{ ...item?.data, key: 'user-' + item?.data?.identityid }],
            onOk: (res: any) => {
              let _item = item;
              _item = {
                ..._item,
                data: {
                  ...item?.data,
                  selectedposition: res[item?.key],
                },
              };
              addItem({
                ..._item.data,
                key: _item.key,
              });
            },
          });
        } else {
          if (checked) {
            addItem({
              ...item.data,
              key: item.key,
            });
          } else {
            removeItem(item.key);
          }
        }
      },
      [addItem, removeItem, multiple, _tabs],
    );

    const change = useCallback(
      (rows) => {
        emit && emit('onBeforeChange', rows);
        $inlineEditContent((rows ?? []).map((ele) => ele.name));
        props.onChange(rows);
      },
      [emit],
    );

    const doSearch = (value: string) => {
      search({
        topNum: pageSize,
        searchContent: value,
        searchDeptId: searchDeptId?.join(','),
        searchPositionId: topPositionIds?.join(','),
        tabs: _tabs.map(getServiceTabKey).join(','),
      })
        .then((res) => {
          if (!timeout) {
            return;
          }
          let _memberList = res.MemberList;
          // 搜索出的用户只用部门的格式
          let _userType = 'department';
          _memberList = _memberList?.map((item: any) => {
            if (item?.MemberArea == 5 && departmentDisplayFormat == 'departments') {
              return {
                ...item,
                deptpathname: '/' + item?.DeptPathName?.replace(/\\/g, '/'),
                usertype: _userType,
              };
            } else if (item?.MemberArea == 4 && positionDisplayFormat == 'departmentsPosition') {
              return {
                ...item,
                deptpathname: '/' + item?.DeptPathName?.replace(/\\/g, '/'),
                usertype: _userType,
              };
            } else if (item?.MemberArea == 0) {
              let _userList = res?.UserList;
              let _item = _userList?.find((item2: any) => item2?.Id == item?.Id);
              return {
                ...item,
                UserMobile: _item?.UserMobile,
                UserTelephone: _item?.UserTelephone,
                usertype: _userType,
              };
            } else {
              return {
                ...item,
                usertype: _userType,
              };
            }
          });
          _searchData((getLowercase(_memberList) || []).map(transSearchData));
          setTimeout(() => {
            _searching(false);
          }, 1000);
        })
        .catch((e) => {
          setTimeout(() => {
            _searching(false);
          }, 1000);
        });
    };

    const handleSearch = (value: string) => {
      _searching(true);
      _searchValue(value);
      clearTimeout(timeout);
      timeout = null;
      if (!value) {
        _searching(false);
        return;
      };
      timeout = setTimeout(() => {
        doSearch(value);
      }, 300);
    };

    const _emptyRender = useMemo(() => {
      if (!searchValue) {
        return getMessage('EformMemberSelect.lang.plzEnterAnotherCharacter');
      }
      if (searching || !timeout) {
        return getMessage('EformMemberSelect.lang.searching');
      }
      if (!searchData?.length) {
        return getMessage('EformMemberSelect.lang.noMatchFound');
      }
      return getMessage('EformMemberSelect.lang.searching');
    }, [searchValue, searchData, searching, timeout]);

    useEffect(() => {
      emit && emit('onLoad', originValue || null);
    }, [originValue]);


    useEffect(() => {
      configEvents.current?.onChange?.(value);
    }, [value]);

    return (
      <div className={'inbiz-EformMemberSelect'}>
        {viewMode != 'look' &&
          <SelectExtend
            className={className}
            viewMode={viewMode}
            selectProps={{
              filterOption: (inputValue = '', option: any) => {
                if (valueKeys.includes(option.value)) {
                  return false;
                }
                return option.children.indexOf(inputValue) > -1;
              },
              mode: multiple ? 'multiple' : 'tags',
              showSearch: true,
              onSearch: handleSearch,
              open,
              searchValue: searchValue,
              onBlur: (e) => {
                _searchValue('');
              },
              onDropdownVisibleChange: (visible) => {
                if (open != visible) {
                  _open(visible);
                  if (!visible) {
                    _searchValue('');
                    _searchData([]);
                  }
                }
              },
              tagRender: (tag) => {
                return (
                  <Tag
                    {...tag}
                    className={`inbiz-EformMemberSelect-inlineTag ${props.readOnly ? 'inlineTagReadOnly' : ''
                      }`}
                    icon={getMemberIconByKey(tag.value?.split('-')[0])}
                    onClose={(e) => {
                      removeItem(tag.value);
                    }}
                    closeIcon={<CloseCircleFilled />}
                    onMouseDown={(e) => {
                      e.stopPropagation();
                    }}
                  >
                    {tag.label}
                  </Tag>
                );
              },
              dropdownRender: (menu) => {
                return (
                  <DropDownRender
                    emptyRender={() => (
                      <div>
                        {_emptyRender}
                      </div>
                    )}
                    iconRender={(item) => getMemberIconByKey(item.key.split('-')[0])}
                    searchValue={searchValue}
                    value={Array.isArray(value) ? value.map((v) => v.key) : []}
                    extra={(item) => {
                      return item.data?.departmentname || item.data?.DeptName || item.data?.deptname;
                    }}
                    data={searchData}
                    onItemClick={onDropdownItemClick}
                  />
                );
              },
              value: multiple ? undefined : Array.isArray(value) ? value?.map?.(transSearchData) : [],
              disabled: other.disabled || other.readOnly || false,
              placeholder: props.readOnly ? '' : <TextWidget>{placeholder}</TextWidget>,
            }}
            addonBefore={
              props.readOnly
                ? undefined
                : {
                  disabled: props.disabled || props.readOnly || false,
                  icon: <PlusCircleOutlined />,
                  // 从组织添加
                  title: getMessage('EformMemberSelect.lang.addFromOrg'),
                  onClick: (e) => {
                    if (_tabs?.length == 0) {
                      return;
                    }
                    emit && emit('onBeforeOpen');
                    _memberSelectVisible(true);
                    emit && emit('onOpen');
                  },
                }
            }
            options={searchData}
            componentIsInline={props.componentIsInline}
            inlineEditContent={inlineEditContent}
          />
        }

        {viewMode == 'look' && value?.length && (!multiple) ? <div style={{ display: 'flex', alignItems: 'center' }}><span style={{ display: 'flex', margin: '0 10px' }}>{getMemberIconByKey(value?.map((item: any) => { return item.key })[0].split('-')[0])}</span><span style={{ fontSize: '12px' }}>{value?.map?.(transSearchData)?.map((item: any) => { return item.label })}</span></div> : ''}
        {props.multiple && Array.isArray(value) && value?.length ? (
          <div
            className={`inbiz-EformMemberSelect-selectedArea ${props.readOnly ? `selectedAreaReadOnly` : ''
              }`}
            style={multiple ? { maxHeight: multipleMaxHeight + 'px', marginTop: viewMode == 'look' ? '-4px' : '', border: viewMode == 'look' ? 'none' : '' } : {}}
          >
            {value.map((item, index) => {
              let _name = nameFormat(
                item,
                departmentDisplayFormat,
                positionDisplayFormat,
                userDepartmentDisplayFormat,
                userUserGroupDisplayFormat,
              );
              let nameArr = [];
              nameArr.push(_name)
              return (
                props.componentIsInline ? (
                  <div className="inbiz-EformMemberSelect-multiple-member">
                    <span>
                      {getMemberIconByKey(item.key?.split('-')[0])} {_name}
                    </span>
                    <span
                      onClick={() => removeItem(item.key)}
                      className="inbiz-EformMemberSelect-multiple-member-icon"
                    >
                      <CloseCircleFilled />
                    </span>
                  </div>
                ) : (
                  viewMode == 'look' ?
                    <Tag
                      icon={getMemberIconByKey(item.key?.split('-')[0])}
                      title={_name}
                      key={item.key}
                      className={'inbiz-MemberSelectTag'}
                    >
                      {_name}
                    </Tag> :
                    <Tag
                      icon={getMemberIconByKey(item.key?.split('-')[0])}
                      title={_name}
                      key={item.key}
                      closable={!props.readOnly}
                      closeIcon={props.readOnly ? null : <CloseCircleFilled />}
                      onClose={(e) => {
                        removeItem(item.key);
                      }}
                      className={'inbiz-MemberSelectTag'}
                    >
                      {_name}
                    </Tag>
                )
              )
            })}
          </div>
        ) : null}
        {memberSelectVisible ? (
          <MemberSelect
            visible={memberSelectVisible}
            modalTitle={props.modalTitle}
            config={{
              callBackEvents,
              emit,
              departmentFilteringRules,
              topDepartmentIds,
              topPositionIds,
              groupFilteringRules,
              groupsIds,
              multiple,
              tabs: _tabs,
              selected: Array.isArray(value) ? value : [],
              collectivization,
              onOk: async (keys, selected, map) => {
                change(selected);
                emit && emit('onBeforeClose', true);
                if (configEvents?.current?.onCustomConfirm) {
                  let result: boolean | undefined | Promise<boolean> = configEvents?.current?.onCustomConfirm(selected);
                  if (result === true) {
                    return;
                  } else {
                    if (typeof result === 'object' && result?.then) {
                      let asyncCustomConfirm = await result?.then();
                      if (asyncCustomConfirm !== true) {
                        _memberSelectVisible(false);
                        emit && emit('onClose', true);
                      };
                    } else {
                      _memberSelectVisible(false);
                      emit && emit('onClose', true);
                    };
                  };
                } else {
                  _memberSelectVisible(false);
                  emit && emit('onClose', true);
                };
              },
              onCancel: () => {
                emit && emit('onBeforeClose', false);
                _memberSelectVisible(false);
                emit && emit('onClose', false);
              },
            }}
          />
        ) : null}
      </div>
    );
  }, { forwardRef: true });

// EformMemberSelect.defaultProps = {
//   // 请选择
//   placeholder: getMessage('EformMemberSelect.lang.plzSelect'),
// };

EformMemberSelect.defaultValueFormat = async (props: any): Promise<void | any[]> => {
  const { defaultValueType, memberDefaultValue, inbiz } = props;
  let _defaultValue: any[] = [];
  if (defaultValueType && (memberDefaultValue || memberDefaultValue == 0)) {
    if (
      defaultValueType == 'department' ||
      defaultValueType == 'user' ||
      defaultValueType == 'group' ||
      defaultValueType == 'position'
    ) {
      _defaultValue = memberDefaultValue;
    } else if (defaultValueType == 'variable') {
      if (
        (memberDefaultValue != 0 && memberDefaultValue != 4 && memberDefaultValue != 5) ||
        _.isEmpty(memberDefaultValue)
      ) {
        return;
      }
      let _userInfoByToken = inbiz?.appInfo?.userInfoByToken;
      let _MainPositionName = _userInfoByToken?.MainPositionName;
      let _MainPositionId = _userInfoByToken?.MainPositionId;
      let _params = [
        {
          memberType: memberDefaultValue,
          memberIds:
            memberDefaultValue == 0
              ? _userInfoByToken.ID
              : memberDefaultValue == 4
                ? _userInfoByToken.MainPositionId
                : _userInfoByToken.MainDepartmentId,
        },
      ];
      let res = await getMemberInfo(_params, {});
      if (res?.result == 0) {
        let result: any[] = [];
        const mapData = (data: any) => {
          data?.map((item: any) => {
            if (item?.memberarea == 0) {
              item['mainpositionname'] = _MainPositionName;
              item['mainpositionid'] = _MainPositionId;
            }
            if (item?.memberarea == 5 || item?.memberarea == 4) {
              let _deptpathname = item?.deptpathname;
              item['deptpathname'] = _deptpathname
                ?.replace(/\\/g, '//')
                ?.split('//')
                ?.filter((item: any) => item)
                ?.join('//');
            }
            let tabKey = getTabKeyByData(item);
            let tabKeyNumber = MemberTypeKeyMap[tabKey];
            if (tabKey != null && tabKeyNumber != null) {
              let key = genKey(tabKey, item);
              item.key = key;
              result.push(item);
            }
          });
        };
        if (!_.isEmpty(res.data.DepartmentInfoList)) {
          let _DepartmentInfoList = getLowercase(res.data.DepartmentInfoList);
          mapData(_DepartmentInfoList);
        }
        if (!_.isEmpty(res.data.GroupInfoList)) {
          let _GroupInfoList = getLowercase(res.data.GroupInfoList);
          mapData(_GroupInfoList);
        }
        if (!_.isEmpty(res.data.PositionInfoList)) {
          let _PositionInfoList = getLowercase(res.data.PositionInfoList);
          mapData(_PositionInfoList);
        }
        if (!_.isEmpty(res.data.UserInfoList)) {
          let _UserInfoList = getLowercase(res.data.UserInfoList);
          mapData(_UserInfoList);
        }
        _defaultValue = result;
      }
    } else {
      _defaultValue = [];
    }
  } else {
    _defaultValue = [];
  }
  return new Promise((resolve, reject) => {
    resolve(_defaultValue);
  });
};

export const getOriginValueFormat = (originValue: string, props: any) => {
  // 单个tab originValue: id || [id,id]
  // 多个tab  originValue: type:id || [type:id,type:id]
  if (!props.childModelConfig && !originValue) {
    return [];
  }

  let tabTypeKey: number | undefined;
  let _tabs: any[] = props?.tabs;
  if (props?.tabs && props?.tabs?.length == 0) {
    _tabs = tabsData;
  }
  if (typeof props?.tabs?.[0] == 'string') {
    _tabs = tabsData?.filter((item: any) => props?.tabs?.includes(item?.memberKey));
  }
  _tabs = _tabs?.filter((item: any) => !item?.hide);
  if (_tabs.length == 1) {
    tabTypeKey = MemberTypeKeyMap[_tabs[0]?.memberKey];
  }
  let typeIds: any[] = [],
    typeObject = {};

  let mapValue: any = originValue ?? '';
  if (!Array.isArray(mapValue)) {
    mapValue = (mapValue || '').split(',');
  }

  let extras: string[] = [];
  let deptIds: string[] = [];
  let positionIds: string[] = [];
  let groupIds: string[] = [];

  mapValue?.map((item2: string) => {
    let _item2 = item2;
    if (item2?.indexOf('&') > -1) {
      let _extras = _item2?.slice(item2?.indexOf('&') + 1);
      _extras.split('&');
      extras = extras?.concat(_extras);
    }
    if (item2?.indexOf('&') == -1 && item2?.indexOf(':') > -1 && item2?.startsWith('5') && _tabs.length > 1) {
      deptIds?.push(_item2?.slice(item2?.indexOf(':') + 1))
    }
    if (item2?.indexOf('&') == -1 && item2?.indexOf(':') > -1 && item2?.startsWith('4') && _tabs.length > 1) {
      positionIds?.push(_item2?.slice(item2?.indexOf(':') + 1))
    }
    if (item2?.indexOf('&') == -1 && item2?.indexOf(':') > -1 && item2?.startsWith('3') && _tabs.length > 1) {
      groupIds?.push(_item2?.slice(item2?.indexOf(':') + 1))
    }
    if (_tabs.length == 1) {
      if (_tabs?.[0]?.memberKey == 'department') {
        deptIds?.push(item2)
      }
      if (_tabs?.[0]?.memberKey == 'position') {
        positionIds?.push(item2)
      }
      if (_tabs?.[0]?.memberKey == 'group') {
        groupIds?.push(item2)
      }
    }
  })

  mapValue = mapValue?.map((item3: string) => {
    let _item3 = item3;
    if (_item3?.indexOf('&') > -1) {
      _item3 = _item3.slice(0, item3?.indexOf('&'));
      return _item3
    } else {
      return item3
    }
  })

  mapValue.map((item: string) => {
    let type, id, extra;
    if (tabTypeKey || tabTypeKey == 0) {
      type = `${tabTypeKey}`;
      if (item?.includes(':')) {
        id = item.split(':')?.[1];
      } else {
        id = item;
      }
    } else {
      const [type1, id1] = item.split(':');
      type = type1;
      id = id1;
    }
    if (type && id) {
      typeIds.push([type, id]);
    }
  });

  if (extras?.length > 0) {
    extras.map((item: string) => {
      let type, id, extra;
      const [type1, id1] = item.split(':');
      type = type1;
      id = id1;
      if (type && id) {
        typeIds.push([type, id]);
      }
    });
  }

  typeIds?.map((item) => {
    if (!typeObject[item[0]]) {
      typeObject[item[0]] = [];
    }
    typeObject[item[0]].push(item[1]);
  });

  let data = Object.keys(typeObject).map((item) => {
    return {
      memberType: item,
      memberIds: typeObject[item].join(','),
    };
  });

  return getMemberInfo(data, props).then((res) => {
    let allObject = {},
      result: any[] = [];
    let typeIdsArr: any[] = [];
    let departmentExtra: any[] = [];
    let positionExtra: any[] = [];
    let groupExtra: any[] = [];
    if (res?.result == 0) {
      let _data = res?.data;
      if (props.childModelConfig) {
        let _tableData = props?.storageConfig?.tableData || [];
        _data = _.map(_data, (item) => {
          let _item = item;
          for (let k = 0; k < _tableData?.length; k++) {
            _item[_tableData[k]?.['componentAttr']] = _item?.[_tableData[k]?.['modelAttr']];
          }
          if (_item?.memberarea == '0') {
            _item['userid'] = _item?.id;
          } else if (_item?.memberarea == '3') {
            _item['groupid'] = _item?.id;
          } else if (_item?.memberarea == '4') {
            _item['positionid'] = _item?.id;
          } else if (_item?.memberarea == '5') {
            _item['deptid'] = _item?.id;
          }
          return _item;
        });
      }
      const mapData = (data: any) => {
        data?.map((item: any) => {
          let tabKey = getTabKeyByData(item);
          let tabKeyNumber = MemberTypeKeyMap[tabKey];
          if (tabKey != null && tabKeyNumber != null) {
            let valueKey = '';
            if (props.childModelConfig) {
              switch (item?.memberarea) {
                case 0:
                case '0':
                  valueKey = tabKeyNumber + ':' + item?.userid;
                  break;
                case 3:
                case '3':
                  valueKey = tabKeyNumber + ':' + item?.groupid;
                  break;
                case 4:
                case '4':
                  valueKey = tabKeyNumber + ':' + item?.positionid;
                  break;
                case 5:
                case '5':
                  valueKey = tabKeyNumber + ':' + item?.deptid;
                  break;
                default:
                  break;
              }
              typeIdsArr.push(valueKey?.split(':'));
            } else {
              valueKey = tabKeyNumber + ':' + item.id;
            }
            let key = genKey(tabKey, item);
            item.key = key;
            allObject[valueKey] = item;
          }
        });
      };
      if (props.childModelConfig) {
        mapData(_data);
      } else {
        if (!_.isEmpty(_data.DepartmentInfoList)) {
          let _DepartmentInfoList = getLowercase(_data.DepartmentInfoList).map((item: any) => {
            return {
              ...item,
              deptpathname: item.deptpathname?.replace(/\\/g, '//')
            }
          });
          let departmentExtras: string[] = extras?.filter((item2: any) => item2?.split(':')[0] == '5') || [];
          if (departmentExtras?.length > 0) {
            let _positionExtras = departmentExtras?.map((item5: any) => item5.slice(item5?.indexOf(':') + 1));
            _DepartmentInfoList = _DepartmentInfoList?.filter((item3: any) => {
              if (_positionExtras?.includes(item3?.id)) {
                departmentExtra?.push(item3);
              }
              if (deptIds?.includes(item3?.id)) {
                return true
              } else {
                return false
              }
            })
          }
          mapData(_DepartmentInfoList);
        }
        if (!_.isEmpty(_data.GroupInfoList)) {
          let _GroupInfoList = getLowercase(_data.GroupInfoList);
          let groupExtras: string[] = extras?.filter((item2: any) => item2?.split(':')[0] == '3') || [];
          if (groupExtras?.length > 0) {
            let _positionExtras = groupExtras?.map((item5: any) => item5.slice(item5?.indexOf(':') + 1));
            _GroupInfoList = _GroupInfoList?.filter((item3: any) => {
              if (_positionExtras?.includes(item3?.id)) {
                groupExtra?.push(item3);
              }
              if (groupIds?.includes(item3?.id)) {
                return true
              } else {
                return false
              }
            })
          }
          mapData(_GroupInfoList);
        }
        if (!_.isEmpty(_data.PositionInfoList)) {
          let _PositionInfoList = getLowercase(_data.PositionInfoList).map((item: any) => {
            return {
              ...item,
              deptpathname: item.deptpathname?.replace(/\\/g, '//')
            }
          });
          let positionExtras: string[] = extras?.filter((item2: any) => item2?.split(':')[0] == '4') || [];
          if (positionExtras?.length > 0) {
            let _positionExtras = positionExtras?.map((item5: any) => item5.slice(item5?.indexOf(':') + 1));
            _PositionInfoList = _PositionInfoList?.filter((item3: any) => {
              if (_positionExtras?.includes(item3?.id)) {
                positionExtra?.push(item3)
              }
              if (positionIds?.includes(item3?.id)) {
                return true
              } else {
                return false
              }
            })
          }
          mapData(_PositionInfoList);
        }
        if (!_.isEmpty(_data.UserInfoList)) {
          let _UserInfoList = getLowercase(_data.UserInfoList);
          let originValueArray = originValue?.split(',')?.filter((item: string) => item?.indexOf('&') > -1);
          let _originValueArray = originValueArray?.map((item1: string) => {
            return [_tabs.length == 1 ? item1?.split('&')[0] : item1?.split('&')[0]?.slice(2), item1?.split('&')[1].slice(2)]
          })
          if (positionExtra && positionExtra?.length > 0) {
            _UserInfoList = _UserInfoList?.map((item3: any) => {
              let _item3 = item3;
              _originValueArray.map((item4: any) => {
                if (item3?.id == item4[0] && positionExtra?.some((item5: any) => item5?.id == item4[1])) {
                  _item3 = {
                    ..._item3,
                    selectedposition: positionExtra?.find((item5: any) => item5?.id == item4[1])?.name,
                  };
                };
              });
              return _item3;
            });
          };
          if (departmentExtra && departmentExtra?.length > 0) {
            _UserInfoList = _UserInfoList?.map((item3: any) => {
              let _item3 = item3;
              _originValueArray.map((item4: any) => {
                if (item3?.id == item4[0] && departmentExtra?.some((item5: any) => item5?.id == item4[1])) {
                  _item3 = {
                    ..._item3,
                    departmentname: _item3?.departmentname || departmentExtra?.find((item5: any) => item5?.id == item4[1])?.name,
                    usertype: 'department',
                  }
                };
              });
              return _item3;
            });
          };
          if (groupExtra && groupExtra?.length > 0) {
            _UserInfoList = _UserInfoList?.map((item3: any) => {
              let _item3 = item3;
              _originValueArray.map((item4: any) => {
                if (item3?.id == item4[0] && groupExtra?.some((item5: any) => item5?.id == item4[1])) {
                  _item3 = {
                    ..._item3,
                    groupname: groupExtra?.find((item5: any) => item5?.id == item4[1])?.name,
                    usertype: 'userGroup',
                  }
                };
              });
              return _item3;
            });
          };
          mapData(_UserInfoList);
        }
      }
    }

    if (props.childModelConfig) {
      typeIdsArr.map((item) => {
        let key = item.join(':');
        if (allObject[key]) {
          result.push(allObject[key]);
        }
      });
    } else {
      typeIds.map((item) => {
        let key = item.join(':');
        if (allObject[key]) {
          result.push(allObject[key]);
        }
      });
    }
    const newResult = new Set(result);
    return [...newResult];
  });
};

EformMemberSelect.originValueFormat = getOriginValueFormat;

EformMemberSelect.displayName = 'EformMemberSelect';
export default EformMemberSelect;
export type { IProps };
